using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace Engine.Serialization
{
    public static class XMLSerializable<T> where T : IXMLSerializable
    {

        private static Dictionary<Type, XmlSerializer> xmlSerializers = new Dictionary<Type,XmlSerializer>();

        public static string Serialize(T serializable)
        {
            XmlSerializer serializer = GetSerializer(typeof(T));

            if (serializer != null)
            {
                TextWriter TW = new StringWriter();
                serializer.Serialize(TW, serializable);
                string xmlData = TW.ToString();
                TW.Close();
                TW.Dispose();
                return xmlData;
            }
            return null;
        }

        public static T Deserialize(string xmlData)
        {
            XmlSerializer deserializer = GetSerializer(typeof(T));

            if (deserializer != null)
            {
                StringReader SR = new StringReader(xmlData);
                XmlReader XR = new XmlTextReader(SR);
                if (deserializer.CanDeserialize(XR))
                {
                    T serializable = (T)deserializer.Deserialize(XR);
                    XR.Close();
                    SR.Close();
                    SR.Dispose();
                    return serializable;
                }
            }
            return default(T);
        }

        private static XmlSerializer GetSerializer(Type type)
        {
            XmlSerializer serializer = null;
            if (xmlSerializers.ContainsKey(type))
            {
                serializer = xmlSerializers[type];
            }
            else
            {
                serializer = new XmlSerializer(type);
                xmlSerializers.Add(type, serializer);
            }
            return serializer;
        }
    }
}
